#include "iosettingwidget.h"
#include "ui_iosettingwidget.h"
//#include <TSettings>
#include "common/tsettings/tsettings.h"
#include "common/common.h"
#include "outputfunction.h"

//const char* IOSettingWidget::OUTPUTSETTINGS = "outputsettings";
const char* IOSettingWidget::DEFAULTOUTPUT = "defaultoutput";
//const char* IOSettingWidget::INTPUTSETTINGS = "inputsettings";
const char* IOSettingWidget::DEFAULTINPUT = "defaultinput";
const char* IOSettingWidget::NO = "NO";
const char* IOSettingWidget::OPERATION = "operation";
const char* IOSettingWidget::NORMALSTATUS = "normalstatus";
const char* IOSettingWidget::DELAYTIME = "delaytime";
const char* IOSettingWidget::CONTINUETIME = "continuetime";
const char* IOSettingWidget::FUNCTION_SET="function";
const char* IOSettingWidget::STATUS_NORMAL_SET="status_res";

IOSettingWidget::IOSettingWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::IOSettingWidget)
{
    ui->setupUi(this);
    setWindowFlags(Qt::FramelessWindowHint);
    setWindowState(Qt::WindowMaximized);
    initOutputWidget();

}

void IOSettingWidget::initOutputWidget()
{
    int outItemCnt = outMgr->outputIoCount();
    for(int i = 0;i<outItemCnt;++i)
    {
        OutputSetItem* item = new OutputSetItem(outMgr->getOutput(i),this);
        mOutSetItemList<<item;
        ui->gridLayout->addWidget(item,i/4,i%4,1,1);
    }
    int inItemCnt = inMgr->inputIoCount();
    for(int i = 0;i<inItemCnt;++i)
    {
        InputSetItem* item = new InputSetItem(inMgr->getInput(i),this);
        mInSetItemList<<item;
        ui->gridLayout_2->addWidget(item,i/4,i%4,1,1);
    }
}

IOSettingWidget::~IOSettingWidget()
{
    delete ui;
}

void IOSettingWidget::on_btn_back_clicked()
{
    this->deleteLater();
}

void IOSettingWidget::on_btn_default_clicked()
{
    int outCnt = outMgr->outputIoCount();
    TSettings set(DIR_SETTINGS,TSettings::IniFormat);
    set.beginReadArray(DEFAULTOUTPUT);
    int defaultOp[outCnt] = {START,HI,OK,LO,BEEP,PICKOUT,NONE};//前6个默认
    for(int i = 0;i<outCnt;++i)
    {
        set.setArrayIndex(i);
        uint operation = set.value(OPERATION,defaultOp[i]).toUInt();
        uint normalStatus = set.value(NORMALSTATUS,NORMALOPEN).toUInt();
        uint delaytime = set.value(DELAYTIME,0).toUInt();
        uint continuetime = set.value(CONTINUETIME,0).toUInt();
        outMgr->saveOutputFunction(i,normalStatus,operation,delaytime,continuetime);
        mOutSetItemList.at(i)->setOptShow();
    }
    set.endArray();
}

void IOSettingWidget::on_btn_default_in_clicked()
{
    TSettings set(DIR_SETTINGS,TSettings::IniFormat);
    int inCnt = inMgr->inputIoCount();
    set.beginReadArray(DEFAULTINPUT);
    for(int i=0;i<inCnt;++i)
    {
        set.setArrayIndex(i);
        uint fn = set.value(FUNCTION_SET,0).toUInt();
        uint normalstaust = set.value(STATUS_NORMAL_SET,NORMALCLOSE).toUInt();
        inMgr->saveInputFunction(i,normalstaust,fn);
        mInSetItemList.at(i)->setOptShow();
    }
    set.endArray();
}
